package megrez.oss.minio;

import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 工具
 * 
 * @author Lucky Yang
 * @since 2.6.9
 */
@Component
public class Utils {
    public final static String TEST_BUCKET = "docexamplebucket12";
    @Autowired
    private ObjectMapper objectMapper;

    public MockMultipartFile createMockMultipartFile(final String fileName) throws IOException {
        Path filePath = Paths.get("src", "test", "resources", fileName);
        return new MockMultipartFile("file", fileName, "multipart/form-data",
                Files.readAllBytes(filePath));
    }

    public String uploadFile(MockMvc mvc, String fileName) throws Exception, IOException {
        MvcResult result = mvc.perform(multipart("/v1//{bucket}/objects/upload", TEST_BUCKET)
                .file(createMockMultipartFile(fileName)).with(csrf()))
                .andDo(print())
                .andExpect(status().isCreated())
                .andReturn();
        return result.getResponse().getContentAsString();
    }

    public <T> T paseObject(String value, TypeReference<T> valueTypeRef) {
        try {
            return objectMapper.readValue(value, valueTypeRef);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

    }

    public <T> T paseObject(String value, Class<T> clazz) {
        try {
            return objectMapper.readValue(value, clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

    }

    public String asJsonString(Object o) {
        try {
            return objectMapper.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
